<template>
  <div class="dashboard-container">
    <!-- 统计卡片 -->
    <el-row :gutter="20" class="stats-row">
      <el-col :xs="24" :sm="12" :md="6">
        <el-card shadow="hover" class="stats-card">
          <div class="stats-icon" style="background-color: #409eff;">
            <i class="el-icon-s-order"></i>
          </div>
          <div class="stats-info">
            <div class="stats-value">{{ stats.totalOrders }}</div>
            <div class="stats-label">今日订单</div>
          </div>
          <div class="stats-trend">
            <span :class="['trend-value', stats.orderTrend >= 0 ? 'up' : 'down']">
              {{ stats.orderTrend >= 0 ? '+' : '' }}{{ stats.orderTrend }}%
            </span>
            <span class="trend-label">较昨日</span>
          </div>
        </el-card>
      </el-col>
      
      <el-col :xs="24" :sm="12" :md="6">
        <el-card shadow="hover" class="stats-card">
          <div class="stats-icon" style="background-color: #67c23a;">
            <i class="el-icon-money"></i>
          </div>
          <div class="stats-info">
            <div class="stats-value">{{ stats.totalSales }}</div>
            <div class="stats-label">今日销售额</div>
          </div>
          <div class="stats-trend">
            <span :class="['trend-value', stats.saleTrend >= 0 ? 'up' : 'down']">
              {{ stats.saleTrend >= 0 ? '+' : '' }}{{ stats.saleTrend }}%
            </span>
            <span class="trend-label">较昨日</span>
          </div>
        </el-card>
      </el-col>
      
      <el-col :xs="24" :sm="12" :md="6">
        <el-card shadow="hover" class="stats-card">
          <div class="stats-icon" style="background-color: #f56c6c;">
            <i class="el-icon-user"></i>
          </div>
          <div class="stats-info">
            <div class="stats-value">{{ stats.newUsers }}</div>
            <div class="stats-label">新增用户</div>
          </div>
          <div class="stats-trend">
            <span :class="['trend-value', stats.userTrend >= 0 ? 'up' : 'down']">
              {{ stats.userTrend >= 0 ? '+' : '' }}{{ stats.userTrend }}%
            </span>
            <span class="trend-label">较昨日</span>
          </div>
        </el-card>
      </el-col>
      
      <el-col :xs="24" :sm="12" :md="6">
        <el-card shadow="hover" class="stats-card">
          <div class="stats-icon" style="background-color: #e6a23c;">
            <i class="el-icon-star-on"></i>
          </div>
          <div class="stats-info">
            <div class="stats-value">{{ stats.averageRating }}</div>
            <div class="stats-label">平均评分</div>
          </div>
          <div class="stats-trend">
            <span :class="['trend-value', stats.ratingTrend >= 0 ? 'up' : 'down']">
              {{ stats.ratingTrend >= 0 ? '+' : '' }}{{ stats.ratingTrend }}%
            </span>
            <span class="trend-label">较昨日</span>
          </div>
        </el-card>
      </el-col>
    </el-row>
    
    <!-- 订单统计图表 -->
    <el-row :gutter="20" class="chart-row">
      <el-col :xs="24" :lg="16">
        <el-card shadow="hover" class="chart-card">
          <div slot="header" class="chart-header">
            <span class="chart-title">订单统计</span>
            <el-radio-group v-model="orderChartPeriod" size="mini">
              <el-radio-button label="today">今日</el-radio-button>
              <el-radio-button label="week">本周</el-radio-button>
              <el-radio-button label="month">本月</el-radio-button>
            </el-radio-group>
          </div>
          <div class="chart-content">
            <div ref="orderChart" class="chart"></div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :xs="24" :lg="8">
        <el-card shadow="hover" class="chart-card">
          <div slot="header" class="chart-header">
            <span class="chart-title">销售额占比</span>
          </div>
          <div class="chart-content">
            <div ref="salesPieChart" class="chart"></div>
          </div>
        </el-card>
      </el-col>
    </el-row>
    
    <!-- 最新订单 -->
    <el-card shadow="hover" class="latest-orders">
      <div slot="header" class="card-header">
        <span>最新订单</span>
        <el-button type="text" @click="$router.push('/orders')">查看全部</el-button>
      </div>
      
      <el-table :data="latestOrders" stripe style="width: 100%" v-loading="loading">
        <el-table-column prop="orderNo" label="订单号" width="180"></el-table-column>
        <el-table-column prop="storeName" label="门店" width="180"></el-table-column>
        <el-table-column prop="userName" label="用户"></el-table-column>
        <el-table-column prop="amount" label="金额" width="120">
          <template slot-scope="scope">
            <span>￥{{ scope.row.amount.toFixed(2) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template slot-scope="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180"></el-table-column>
        <el-table-column label="操作" width="120">
          <template slot-scope="scope">
            <el-button type="text" size="mini" @click="viewOrderDetail(scope.row.id)">查看</el-button>
            <el-button 
              v-if="scope.row.status === 'PAID'" 
              type="text" 
              size="mini" 
              @click="processOrder(scope.row.id)">处理</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script>
import * as echarts from 'echarts';

export default {
  name: 'Dashboard',
  data() {
    return {
      loading: false,
      orderChartPeriod: 'today',
      stats: {
        totalOrders: 0,
        totalSales: 0,
        newUsers: 0,
        averageRating: 0,
        orderTrend: 0,
        saleTrend: 0,
        userTrend: 0,
        ratingTrend: 0
      },
      latestOrders: [],
      orderChart: null,
      salesPieChart: null
    };
  },
  mounted() {
    this.fetchDashboardData();
    this.initCharts();
    
    // 监听窗口大小变化，重新渲染图表
    window.addEventListener('resize', this.resizeCharts);
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.resizeCharts);
    
    // 销毁图表实例
    if (this.orderChart) {
      this.orderChart.dispose();
    }
    if (this.salesPieChart) {
      this.salesPieChart.dispose();
    }
  },
  watch: {
    orderChartPeriod() {
      this.updateOrderChart();
    }
  },
  methods: {
    fetchDashboardData() {
      this.loading = true;
      
      // 模拟API请求
      setTimeout(() => {
        // 统计数据
        this.stats = {
          totalOrders: 156,
          totalSales: '¥12,350.00',
          newUsers: 35,
          averageRating: 4.8,
          orderTrend: 12.5,
          saleTrend: 8.3,
          userTrend: -3.2,
          ratingTrend: 2.1
        };
        
        // 最新订单
        this.latestOrders = [
          {
            id: 1,
            orderNo: 'SO2023051200001',
            storeName: '麦当劳(广场店)',
            userName: '张三',
            amount: 45.5,
            status: 'COMPLETED',
            createTime: '2023-05-12 12:30:45'
          },
          {
            id: 2,
            orderNo: 'SO2023051200002',
            storeName: '肯德基(商场店)',
            userName: '李四',
            amount: 68.0,
            status: 'PAID',
            createTime: '2023-05-12 13:20:18'
          },
          {
            id: 3,
            orderNo: 'SO2023051200003',
            storeName: '必胜客(北门店)',
            userName: '王五',
            amount: 128.5,
            status: 'DELIVERING',
            createTime: '2023-05-12 14:05:36'
          },
          {
            id: 4,
            orderNo: 'SO2023051200004',
            storeName: '星巴克(西湖店)',
            userName: '赵六',
            amount: 35.0,
            status: 'PENDING',
            createTime: '2023-05-12 14:30:22'
          },
          {
            id: 5,
            orderNo: 'SO2023051200005',
            storeName: '麦当劳(广场店)',
            userName: '钱七',
            amount: 72.5,
            status: 'PAID',
            createTime: '2023-05-12 15:10:08'
          }
        ];
        
        this.loading = false;
        
        // 更新图表数据
        this.updateOrderChart();
        this.updateSalesPieChart();
      }, 1000);
    },
    
    initCharts() {
      // 初始化订单统计图表
      this.orderChart = echarts.init(this.$refs.orderChart);
      
      // 初始化销售额占比图表
      this.salesPieChart = echarts.init(this.$refs.salesPieChart);
    },
    
    resizeCharts() {
      if (this.orderChart) {
        this.orderChart.resize();
      }
      if (this.salesPieChart) {
        this.salesPieChart.resize();
      }
    },
    
    updateOrderChart() {
      let xAxisData = [];
      let seriesData = [];
      
      // 根据选择的时间段生成数据
      if (this.orderChartPeriod === 'today') {
        xAxisData = ['00:00', '02:00', '04:00', '06:00', '08:00', '10:00', '12:00', '14:00', '16:00', '18:00', '20:00', '22:00'];
        seriesData = [5, 3, 2, 4, 10, 15, 25, 30, 20, 18, 12, 8];
      } else if (this.orderChartPeriod === 'week') {
        xAxisData = ['周一', '周二', '周三', '周四', '周五', '周六', '周日'];
        seriesData = [120, 132, 101, 134, 90, 230, 210];
      } else if (this.orderChartPeriod === 'month') {
        xAxisData = Array.from({length: 30}, (_, i) => `${i + 1}日`);
        seriesData = Array.from({length: 30}, () => Math.floor(Math.random() * 200 + 50));
      }
      
      const option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: xAxisData,
          axisLine: {
            lineStyle: {
              color: '#999'
            }
          },
          axisLabel: {
            color: '#666'
          }
        },
        yAxis: {
          type: 'value',
          axisLine: {
            show: false
          },
          axisLabel: {
            color: '#666'
          },
          splitLine: {
            lineStyle: {
              color: '#eee'
            }
          }
        },
        series: [
          {
            name: '订单数',
            type: 'bar',
            barWidth: '60%',
            data: seriesData,
            itemStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: '#83bff6' },
                { offset: 0.5, color: '#188df0' },
                { offset: 1, color: '#188df0' }
              ])
            }
          }
        ]
      };
      
      this.orderChart.setOption(option);
    },
    
    updateSalesPieChart() {
      const option = {
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        legend: {
          orient: 'vertical',
          right: 10,
          top: 'center',
          data: ['麦当劳', '肯德基', '必胜客', '星巴克', '其他']
        },
        series: [
          {
            name: '销售额',
            type: 'pie',
            radius: ['50%', '70%'],
            avoidLabelOverlap: false,
            label: {
              show: false,
              position: 'center'
            },
            emphasis: {
              label: {
                show: true,
                fontSize: '16',
                fontWeight: 'bold'
              }
            },
            labelLine: {
              show: false
            },
            data: [
              { value: 35, name: '麦当劳' },
              { value: 25, name: '肯德基' },
              { value: 20, name: '必胜客' },
              { value: 15, name: '星巴克' },
              { value: 5, name: '其他' }
            ]
          }
        ]
      };
      
      this.salesPieChart.setOption(option);
    },
    
    getStatusType(status) {
      const statusMap = {
        'PENDING': 'info',
        'PAID': 'warning',
        'PREPARING': 'warning',
        'DELIVERING': 'primary',
        'COMPLETED': 'success',
        'CANCELLED': 'danger'
      };
      return statusMap[status] || 'info';
    },
    
    getStatusText(status) {
      const statusMap = {
        'PENDING': '待付款',
        'PAID': '已付款',
        'PREPARING': '制作中',
        'DELIVERING': '配送中',
        'COMPLETED': '已完成',
        'CANCELLED': '已取消'
      };
      return statusMap[status] || status;
    },
    
    viewOrderDetail(orderId) {
      this.$router.push(`/orders/${orderId}`);
    },
    
    processOrder(orderId) {
      this.$confirm('确认开始处理此订单?', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 模拟API请求
        this.$message({
          type: 'success',
          message: '订单已开始处理'
        });
        
        // 更新订单状态
        const index = this.latestOrders.findIndex(order => order.id === orderId);
        if (index !== -1) {
          this.latestOrders[index].status = 'PREPARING';
        }
      }).catch(() => {
        // 取消操作
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.dashboard-container {
  padding: 20px;
  
  .stats-row {
    margin-bottom: 20px;
  }
  
  .stats-card {
    display: flex;
    align-items: center;
    padding: 20px;
    height: 120px;
    margin-bottom: 20px;
    
    .stats-icon {
      width: 60px;
      height: 60px;
      border-radius: 8px;
      display: flex;
      justify-content: center;
      align-items: center;
      margin-right: 15px;
      
      i {
        font-size: 28px;
        color: #fff;
      }
    }
    
    .stats-info {
      flex: 1;
      
      .stats-value {
        font-size: 24px;
        font-weight: bold;
        color: #303133;
        margin-bottom: 5px;
      }
      
      .stats-label {
        font-size: 14px;
        color: #909399;
      }
    }
    
    .stats-trend {
      text-align: right;
      
      .trend-value {
        display: block;
        font-size: 16px;
        margin-bottom: 5px;
        
        &.up {
          color: #67c23a;
        }
        
        &.down {
          color: #f56c6c;
        }
      }
      
      .trend-label {
        font-size: 12px;
        color: #909399;
      }
    }
  }
  
  .chart-row {
    margin-bottom: 20px;
  }
  
  .chart-card {
    margin-bottom: 20px;
    
    .chart-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      
      .chart-title {
        font-size: 16px;
        font-weight: bold;
        color: #303133;
      }
    }
    
    .chart-content {
      padding: 10px 0;
      
      .chart {
        width: 100%;
        height: 350px;
      }
    }
  }
  
  .latest-orders {
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      font-size: 16px;
      font-weight: bold;
      color: #303133;
    }
  }
}

// 移动端适配
@media screen and (max-width: 768px) {
  .dashboard-container {
    padding: 10px;
    
    .stats-card {
      height: auto;
      
      .stats-icon {
        width: 50px;
        height: 50px;
        
        i {
          font-size: 24px;
        }
      }
      
      .stats-info {
        .stats-value {
          font-size: 20px;
        }
      }
      
      .stats-trend {
        .trend-value {
          font-size: 14px;
        }
      }
    }
    
    .chart-content {
      .chart {
        height: 250px;
      }
    }
  }
}
</style> 